from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from monitor import models
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
# Create your views here.
import urllib.parse
import sys
import html
import re


#转化为中文
def unescape(string):
    string = urllib.parse.unquote(string)
    quoted = html.unescape(string).encode(sys.getfilesystemencoding()).decode('utf-8')
    return re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), quoted)
def callback(request):
    if  request.method == "POST":
        data = unescape(request.body.decode()).split('&')
        d = dict()
        for i in data:
            if "instanceName" in i:
                d["instanceName"] = i.split("=")[1]
            elif "metricName" in i:
                d["metricName"] = i.split("=")[1]
            elif "curValue" in i:
                d["curValue"] = i.split("=")[1]
            # 报警级别
            elif "triggerLevel" in i:
                d["triggerLevel"] = i.split("=")[1]
            # 发生报警的对象
            elif "dimensions" in i:
                d["dimensions"] = i.replace('dimensions=', '')
        models.Monitor.objects.create(**d)
        return HttpResponse("200")
    elif request.method == "GET":
        return HttpResponse("<h1>Hello World</h1>")

def recordtable(request):
    if not request.session.get("user_id", None):
        return  redirect("/users/login")
    return render(request,"recordtable.html")

def recordjson(request):
    data=list()
    for m in models.Monitor.objects.all():
        d=dict()
        d["id"]=m.id
        d["instanceName"]=m.instanceName
        d["metricName"]=m.metricName
        d["curValue"]=m.curValue
        d["triggerLevel"]=m.triggerLevel
        d["dimensions"] = m.dimensions
        d["timestamp"] = m.timestamp
        data.append(d)
    redata= {"code": 0, "msg": "", "count": len(data),"data":data}
    return JsonResponse(redata,safe=False)

def kinanaCallback(request):
    data="jeff"
    if request.method == "POST":
        d = dict()
        data=request.body.decode()
        data=eval(data)
        d["type"] = data["type"]
        d["project"] = data["project"]
        key = list()
        value = list()
        n = 1
        for i in data["value"].split(','):
            if 'value' in i:
                value.append(i.replace('%d={value=' % (n - 1), '').replace('{', '').replace(' ', ''))
                n += 1
            else:
                key.append(i.replace(' key=', '').replace('}', ''))
        d["value"] = dictionary = dict(zip(key, value))
        obj=models.Logerror(type=data["type"],project=data["project"],value=data['value'])
        obj.save()
    return HttpResponse("ok")

def errorLogtable(request):
    pass

